import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * LoadBalancer方式
 */
@Component
@Slf4j
public class NacosServiceInstanceChangeNotifier extends Subscriber<InstancesChangeEvent> {
    /**
     * 由于会有多个类型的 CacheManager bean, 这里的 defaultLoadBalancerCacheManager 名称不可修改
     */
    @Resource
    private CacheManager defaultLoadBalancerCacheManager;

    @PostConstruct
    public void registerToNotifyCenter() {
        NotifyCenter.registerSubscriber(this);
    }

    @Override
    public void onEvent(InstancesChangeEvent event) {
        log.info("监听nacos的服务实例变化情况:{}", JSON.toJSONString(event));
        String serviceName = event.getServiceName();
        log.info("服务上下线: {}", serviceName);
        // 使用 dubbo 时包含 rpc 服务类会注册以 providers: 或者 consumers: 开头的服务
        // 由于不是正式的服务, 这里需要进行排除, 如果未使用 dubbo 则不需要该处理
        if (serviceName.contains(Constants.COLON)) {
            // serviceName 格式为 groupName::name
            serviceName = serviceName.split(Constants.COLON)[1];
        } else if (serviceName.contains(Constants.SERVICE_INFO_SPLITER)) {
            // serviceName 格式为 groupName@@name
            serviceName = serviceName.substring(serviceName.indexOf(Constants.SERVICE_INFO_SPLITER)
                    + Constants.SERVICE_INFO_SPLITER.length());
        } else {
            return;
        }

        // 手动更新服务列表
        Cache cache = defaultLoadBalancerCacheManager.getCache(CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME);
        if (cache != null) {
            cache.evictIfPresent(serviceName);
        }
    }

    @Override
    public Class<? extends Event> subscribeType() {
        return InstancesChangeEvent.class;
    }
}